<?php
include_once '../conn.php';

// 分页参数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$perPage = 10; // 每页显示的用户数

// 搜索参数
$search = isset($_GET['search']) ? $_GET['search'] : '';

// 计算起始偏移量
$offset = ($page - 1) * $perPage;

// 构建查询语句
$query = "SELECT * FROM users";

// 添加搜索条件
if (!empty($search)) {
    $query .= " WHERE username LIKE '%$search%' OR email LIKE '%$search%'";
}

// 添加分页条件
$query .= " LIMIT $perPage OFFSET $offset";

// 执行查询
$result = $conn->query($query);

// 获取总记录数
$totalQuery = "SELECT COUNT(*) as total FROM users";
if (!empty($search)) {
    $totalQuery .= " WHERE username LIKE '%$search%' OR email LIKE '%$search%'";
}
$totalResult = $conn->query($totalQuery);
$total = $totalResult->fetch_assoc()['total'];

// 构建响应数组
$response = array();
$response['users'] = array();
 
// 将查询结果添加到响应数组
while ($row = $result->fetch_assoc()) {
    $user = array(
        'user_id' => $row['user_id'],
        'image_path' => $row['image_path'],
        'username' => $row['username'],
        'email' => $row['email'],
        'phone' => $row['phone'],
        'registration_date' => $row['registration_date'],
    );
    $response['users'][] = $user;
}

// 添加总页数到响应数组
$response['total_pages'] = ceil($total / $perPage);

// 输出 JSON 格式的响应
header('Content-Type: application/json');
echo json_encode($response);

// 关闭数据库连接
$conn->close();
?>
